using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;

namespace Axe.Web.HttpModules
{
    /// <summary>
    /// Summary description for RefreshAction
    /// </summary>
    public class RefreshAction
    {
        static Dictionary<string, int> requestHistory = new Dictionary<string, int>();

        public static readonly string NextPageTicketEntry = "NextPageTicketEntry";
        public static readonly string CurrentRefreshTicketEntry = "CurrentRefreshTicketEntry";
        public static readonly string PageRefreshEntry = "PageRefreshEntry";

        public static void Check(HttpContext ctx)
        {

            int lastTicket = GetLastRefreshTicket(ctx);

            int thisTicket = GetCurrentRefreshTicket(ctx, lastTicket);

            if (thisTicket > lastTicket ||
                (thisTicket == lastTicket && thisTicket == 0))
            {
                UpdateLastRefreshTicket(ctx, thisTicket);
                ctx.Items[RefreshAction.PageRefreshEntry] = false;
            }
            else
            {
                ctx.Items[PageRefreshEntry] = true;
            }
        }


        static int GetLastRefreshTicket(HttpContext ctx)
        {
            if (!requestHistory.ContainsKey(ctx.Request.Path))
                return 0;
            else
                return (int)requestHistory[ctx.Request.Path];
        }

        static int GetCurrentRefreshTicket(HttpContext ctx, int lastTicket)
        {
            int ticket;
            object o = ctx.Request[CurrentRefreshTicketEntry];
            if (o == null)
            {
                ticket = lastTicket;
            }
            else
            {
                ticket = Convert.ToInt32(o);
            }

            ctx.Items[RefreshAction.NextPageTicketEntry] = ticket + 1;
            return ticket;
        }

        static void UpdateLastRefreshTicket(HttpContext ctx, int ticket)
        {
            requestHistory[ctx.Request.Path] = ticket;
        }

        public RefreshAction()
        {
        }
    }
}